package com.wonders.framework.dao.sequence;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.Date;

import org.hibernate.HibernateException;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.id.SequenceGenerator;

import com.wonders.framework.exception.FrameworkException;

/**
 * 日期序列生成器
 * 
 * @author WuBin
 * 
 */
public class DateSequenceGenerator extends SequenceGenerator {

	private final static DecimalFormat decimalFormatSeq = new DecimalFormat(
			"00000");

	private final static DecimalFormat decimalFormatSeconds = new DecimalFormat(
			"0000000000");

	@Override
	public Serializable generate(SessionImplementor arg0, Object arg1)
			throws HibernateException {
		try {
			Serializable seq = super.generate(arg0, arg1);
			StringBuilder sb = new StringBuilder();
			long seconds = new Date().getTime() / 1000;
			sb.append(decimalFormatSeconds.format(seconds));
			sb.append(decimalFormatSeq.format(seq));
			return Long.parseLong(sb.toString());
		} catch (Exception e) {
			throw new FrameworkException("主键生成失败", e);
		}

	}
}
